package dao

import (
	"github.com/crack007/go-im/src/common/entity"
	"github.com/crack007/go-im/src/common/util"
	"gorm.io/gorm"
)

type applyDao struct {
	db *gorm.DB
}

func (d *applyDao) ListByFromId(fromId uint32) []*entity.ApplyEntity {
	var list []*entity.ApplyEntity
	d.db.Where("is_delete=0 and from_id=?", fromId).Find(&list)
	return list
}

func (d *applyDao) ListByToId(toId uint32, page uint32, size uint32) []*entity.ApplyEntity {
	var list []*entity.ApplyEntity
	offset := (page - 1) * size
	d.db.Where("is_delete=0 and to_id=?", toId).Limit(int(size)).Offset(int(offset)).Find(&list)
	return list
}

func (d *applyDao) GetByFromIdAndToId(fromId uint32, toId uint32) *entity.ApplyEntity {
	var applyEntity *entity.ApplyEntity
	d.db.Where("is_delete=0 and from_id=? and to_id=?", fromId, toId).Find(&applyEntity)
	if applyEntity.ID == 0 {
		return nil
	}
	return applyEntity
}

func (d *applyDao) Save(applyEntity *entity.ApplyEntity) {
	if applyEntity.ID > 0 {
		applyEntity.UpdatedAt = util.GetDatetime()
	}
	d.db.Save(applyEntity)
}

func (d *applyDao) GetById(id uint32) *entity.ApplyEntity {
	var applyEntity *entity.ApplyEntity
	d.db.Where("id=?", id).Find(&applyEntity)
	if applyEntity.ID == 0 || applyEntity.IsDelete {
		return nil
	}
	return applyEntity
}
